For the following exercises we will also data from Gapminder; this time on life expectancy.
As per usual, we first need to read in the data. You can just copy, paste and run the following code in(to) your script.
library(readr)
gap_life <- read_csv("../data/gapminder/life_expectancy_years.csv")
## Parsed with column specification:
## cols(
## .default = col_double(),
## country = col_character()
## )
## See spec(...) for full column specifications.
Again, the data are currently in wide format.
starts_with(). We also want to keep the country column.
As you may have already noticed, the dataset some missing data points. Before we start analyzing the data we might want to know for how many countries we have complete data.
drop_na() function from tidyr.
As in the previous set of data wrangling exercises, we now want to transform the data into long format.
Now let’s apply some of the advanced filtering options we discussed in the Data Wrangling - Part 2 session.
gap_life <- gap_life %>%
mutate(country = as.factor(country),
year = as.integer(year))
dplyr to create the first new dataframe and a specific matching operator to create the second one.
For some comparisons (especially via plots), it might help to know which continent the country is located on. For this purpose, we will create a new continent variable. As it would be quite tedious to create this variable manually for all of the countries in the dataset, we will do this only for a subset in this exercise. Just run the following code in your local script to create this subset.
gap_life_subset <- gap_life %>%
filter(country %in%
c("Netherlands", "Brazil", "China", "Algeria", "New Zealand"))
case_when() to create this new variable.